package com.newhero.product.module.sys.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.newhero.product.common.controller.BaseController;
import com.newhero.product.common.mybatis.mapper.EntityWrapper;
import com.newhero.product.common.mybatis.plugins.Page;
import com.newhero.product.common.util.BeanUtils;
import com.newhero.product.common.util.DigestUtils;
import com.newhero.product.common.util.StringUtils;
import com.newhero.product.common.vo.ZTreeModel;
import com.newhero.product.module.sys.model.Organ;
import com.newhero.product.module.sys.model.Role;
import com.newhero.product.module.sys.model.User;
import com.newhero.product.module.sys.model.vo.UserVo;
import com.newhero.product.module.sys.service.IOrganService;
import com.newhero.product.module.sys.service.IUserService;

/**
 * @ClassName: UserController
 * @Description: 用户管理控制类
 * @author Caolj 648198687@qq.com
 * @date 2017-4-17 上午10:35:06
 */
@Controller
@RequestMapping("/admin")
public class UserController extends BaseController {
	@Autowired
	private IOrganService organServiceImpl;
	@Autowired
	private IUserService userServiceImpl;

	private static final int _ROWS = 10;

	@RequestMapping(value = "/user", method = RequestMethod.GET)
	public String user(HttpServletRequest request) {
		return "sys/user/user";
	}

	@ResponseBody
	@RequestMapping(value = "/organTreeForUser", method = RequestMethod.POST)
	public List<ZTreeModel> organTreeForUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String organID = super.getOrganID();
		List<Organ> organList = organServiceImpl.recursionOrganList(organID);
		List<ZTreeModel> treeList = new ArrayList<ZTreeModel>();

		for (Organ organ : organList) {
			ZTreeModel atm;
			if (organ.getOrganPID() == null || "".equals(organ.getOrganPID())) {
				atm = new ZTreeModel(organ.getOrganID(), organ.getOrganPID(),
						organ.getOrganName(), true, "");
			} else {
				atm = new ZTreeModel(organ.getOrganID(), organ.getOrganPID(),
						organ.getOrganName(), false, "");
			}
			if (organ.getOrganType() != null && organ.getOrganType() == 10) {
				atm.setIcon(request.getContextPath()
						+ "/static/zTree_v3/css/ext_icons/building.png");
			} else {
				atm.setIcon(request.getContextPath()
						+ "/static/zTree_v3/css/ext_icons/door.png");
			}
			treeList.add(atm);
		}
		return treeList;
	}

	@RequestMapping(value = "/userForList", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String userForList(
			@RequestParam(value = "page", defaultValue = "1", required = true) int page,// 页号
			@RequestParam(value = "rows", defaultValue = "" + _ROWS, required = true) int rows,// 每页显示的记录条数
			@RequestParam(value = "userName", defaultValue = "", required = false) String userName,
			@RequestParam(value = "organID", defaultValue = "", required = false) String organID,
			@RequestParam(value = "organID_V", defaultValue = "", required = false) String organID_V,
			@RequestParam(value = "userLoginName", defaultValue = "", required = false) String userLoginName,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {

		Page<UserVo> p = new Page<UserVo>();
		p.setCurrent(page);
		p.setSize(rows);
		p.setOrderByField("userOrder");

		Map<String, Object> params = new HashMap<String, Object>();

		if (StringUtils.isNotBlank(userName)) {
			params.put("userName", userName);
		}
		if (StringUtils.isNotBlank(userLoginName)) {
			params.put("userLoginName", userLoginName);
		}
		if (StringUtils.isNotBlank(organID)) {
			params.put("organID", organID);
		}

		p.setRecords(userServiceImpl.selectUserVoPage(p, params));
		model.addAttribute("data", p);
		model.addAttribute("userName", userName);
		model.addAttribute("organID", organID);
		model.addAttribute("organID_V", organID_V);
		model.addAttribute("userLoginName", userLoginName);
		return "sys/user/userForList";
	}

	@RequestMapping(value = "/userDelete", method = { RequestMethod.POST,
			RequestMethod.GET })
	public String userDelete(
			@RequestParam(value = "ids", required = true) String ids,
			@RequestParam(value = "organID", defaultValue = "", required = false) String organID,
			@RequestParam(value = "userName", defaultValue = "", required = false) String userName,
			@RequestParam(value = "userLoginName", defaultValue = "", required = false) String userLoginName,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		String[] idArr = ids.split(",");
		userServiceImpl.deleteBatchIds(idArr);

		model.addAttribute("flag", "数据删除成功！");
		return userForList(1, _ROWS, userName, "", "", userLoginName, request,
				response, model);
	}

	@RequestMapping(value = "/userForm", method = RequestMethod.GET)
	public String sysUserForm(
			@RequestParam(value = "userID", defaultValue = "", required = true) String userID,
			@RequestParam(value = "userName", defaultValue = "", required = false) String userName,
			@RequestParam(value = "userLoginName", defaultValue = "", required = false) String userLoginName,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		if (userID != null && !"".equals(userID)) {
			User su = userServiceImpl.selectById(userID);
			request.setAttribute("formData", su);
			request.setAttribute("userID", userID);
			String organID = su.getOrganID();
			request.setAttribute("organName",
					organServiceImpl.selectById(organID).getOrganName());
		} else {
			request.setAttribute("userID", "");
		}
		request.setAttribute("userLoginName", userLoginName);
		request.setAttribute("userName", userName);
		return "sys/user/userForm";
	}

	@ResponseBody
	@RequestMapping(value = "/loginNameExsit", method = RequestMethod.POST)
	public boolean loginNameExsit(
			@RequestParam(value = "userID", defaultValue = "", required = true) String userID,
			@RequestParam(value = "userLoginName", defaultValue = "", required = true) String userLoginName,
			HttpServletRequest request, HttpServletResponse response) {
		boolean flag = userServiceImpl.checkIfUserLoginNameExsit(userID,
				userLoginName);
		System.out.println(flag + "<><><><><>");
		return flag;
	}

	// @RequestMapping(value = "/checkPwd", method = RequestMethod.POST)
	// public void checkPwd(
	// @RequestParam(value = "userPwd", defaultValue = "", required = true)
	// String userPwd,
	// @RequestParam(value = "userPwd2", defaultValue = "", required = true)
	// String userPwd2,
	// HttpServletRequest request, HttpServletResponse response) {
	// boolean result = true;
	// if (!userPwd.equals(userPwd2)) {
	// result = false;
	// }
	// writeJson(request, response, result);
	// }
	//
	@RequestMapping(value = "/userSave", method = RequestMethod.POST)
	public String userSave(
			String userID,
			@RequestParam(value = "organID", defaultValue = "", required = false) String organID,
			User user, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		try {
			if (!StringUtils.isBlank(userID)) {
				if (!organID.equals("")) {
					user.setOrganID(organID);
				}
				User su = userServiceImpl.selectById(userID);
				BeanUtils.copy(user, su);
				userServiceImpl.updateById(su);
				model.addAttribute("flag", "用户修改成功");
			} else {
				String password = user.getUserPwd();
				if (!organID.equals("")) {
					user.setOrganID(organID);
				}
				user.setUserPwd(DigestUtils.md5Hex(password));
				userServiceImpl.insert(user);
				model.addAttribute("flag", "用户添加成功");
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return "redirect:userForList";
	}

	@RequestMapping(value = "/editpasswd", method = RequestMethod.GET)
	public String editpasswd(
			@RequestParam(value = "userID", required = true) String userID,
			HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute("userID", userID);
		return "sys/user/passwdForm";
	}

	@RequestMapping(value = "/passwdSave", method = RequestMethod.POST)
	@ResponseBody
	public Object myPasswordSave(
			@RequestParam(value = "newpwd", required = true) String newpwd,
			@RequestParam(value = "userID", required = true) String userID,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		if (userID != null) {
			User su = userServiceImpl.selectById(userID);
			userServiceImpl.updatePwdByUserId(userID,DigestUtils.md5Hex(newpwd));
				return renderSuccess("密码修改成功！");
		} else {
			return renderError("旧密码不正确！");
		}

	}

	//
	// @RequestMapping(value = "/passwdSave", method = RequestMethod.POST)
	// public void myPasswordSave(@RequestParam(value = "newpwd", required =
	// true) String newpwd,
	// @RequestParam(value = "userID", required = true) String userID,
	// HttpServletRequest request,
	// HttpServletResponse response, ModelMap model) {
	// Json json = new Json();
	// try {
	// if (userID != null) {
	// SysUser su = userServiceImpl.getById(userID);
	// su.setUserPwd(Encryption.encryption(newpwd));
	// userServiceImpl.saveOrUpdate(su);
	// json.setMsg("密码修改成功！");
	// }
	//
	// json.setSuccess(true);
	// }
	// catch (Exception e) {
	// logger.error(e);
	// json.setMsg("密码修改失败！");
	// e.printStackTrace();
	// }
	// writeJson(request, response, json);
	// }

	@RequestMapping(value = "/userEdit", method = RequestMethod.POST)
	public void userEdit(
			@RequestParam(value = "userID", required = true) String userID,
			HttpServletRequest request, HttpServletResponse response) {
		User user = userServiceImpl.selectById(userID);
		renderSuccess(user);
	}

}
